package com.jfinal.core;

import java.text.ParseException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;



public class BaseController extends Controller {
	/**
	 * 来自小木学堂的解决方案
	 * @param modelClass
	 * @return
	 */
	public <T> T getNoDomainModal(Class<T> modelClass){
			//获得参数map
			Map<String, String[]> map= getRequest().getParameterMap();
			Iterator<Entry<String, String[]>> it=map.entrySet().iterator();
			Entry<String, String[]> e=null;
			Model modal=null;
			try {
				modal = (Model) modelClass.newInstance();
			} catch (InstantiationException e1) {
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			}
			//获得表结构
			Table table=TableMapping.me().getTable(modal.getClass());
			//循环遍历参数 构造modal
			while(it.hasNext()){
				e=it.next();
				//判断表单参数名和table字段名称相同的可以装配
				if(table.hasColumnLabel(e.getKey())){
					//获得字段类型
					Class colType = table.getColumnType(e.getKey());
					if (colType == null)
						throw new ActiveRecordException("The model attribute " + e.getKey() + " is not exists.");
					//获得字段值
					String[] paraValue = e.getValue();
					Object value=null;
					try {
						value = paraValue[0] != null ? TypeConverter.convert(colType, paraValue[0]) : null;
					} catch (ParseException e1) {
						e1.printStackTrace();
					}
					//最后赋值
					modal.set(e.getKey(), value);
				}
			}
			return  (T)modal;
	}
	/** 
	 * 通用request获取当前对象model 来自开源中国的解决方法
	 * @return 
	 * @throws Exception 
	 */ 
	 /*protected Model<M> getCustomModel() throws Exception { 
	 HttpServletRequest request = this.getRequest(); 
	 Model<M> model_ = Student.class.newInstance(); 
	 model_.getAttrNames(); 
	 Enumeration<String> attrNames = request.getParameterNames(); 
	 while(attrNames.hasMoreElements()) { 
	 String key = attrNames.nextElement(); 
	 String value=request.getParameter(key); 
	 model_.set(key, value); 
	 } 
	 return model_; 

	} */
	public void read() {
		
	}
	public void remove() {
		
	}
	public void createOrUpdate() {
		
	}
}
